package com.baseproject.datasource.get.request.type;

import com.baseproject.datasource.get.procedure.DataProcedure;
import com.baseproject.datasource.get.response.BaseResponseHandler;
import com.baseproject.datasource.local.LocalDataSource;
import com.baseproject.json.JsonUtils;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by hp on 2017/8/18.
 */

public class ObjectRequestType extends RequestType {


    @Override
    public <T> void save(List<T> contentList, DataProcedure dataProcedure) {
        String uniqueKey = dataProcedure.getUniqueKey();
        if (null != jsonObjectData) {
            LocalDataSource.getInstance().saveObjectIntoFile(jsonObjectData, uniqueKey)
                    .subscribe(new Subscriber<Boolean>() {
                        @Override
                        public void onCompleted() {
                        }
                        @Override
                        public void onError(Throwable e) {
                        }
                        @Override
                        public void onNext(Boolean aBoolean) {
                        }
                    });
        }
    }

    @Override
    public <T> List<T> getListFromRemoteResponseData(Object objectData, Class<T> className) {
        jsonObjectData = BaseResponseHandler.createResponseHandler(objectData).getJSONObjectData();
        if (null != jsonObjectData) {
            List<T> contentList = new ArrayList<T>();
            T t = JsonUtils.getInstance().strToModel(jsonObjectData.toString(), className);
            contentList.add(t);
            return contentList;
        }
        return null;
    }

    protected void saveToFile(Object objectData, String uniqueKey) {

    }

    @Override
    public <T> Observable<List<T>> getListFromLocal(DataProcedure dataProcedure, Class<T> className) {
        String fileName = dataProcedure.getLocalRequestParams().getUniqueKey();
        return LocalDataSource.getInstance().getObjectInternal(fileName, className)
                .map(new Func1<T, List<T>>() {
                    @Override
                    public List<T> call(T localObject) {
                        List<T> contentList = null;
                        if (localObject != null) {
                            contentList = new ArrayList<T>() {{add((T) localObject);}};
                        }
                        return contentList;
                    }
                });
    }
}
